package org.surelink.radius.middleware.acct;


import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.surelink.radius.cache.OnlineCache;
import org.surelink.radius.cache.UserCache;
import org.surelink.radius.middleware.AcctMiddleware;
import org.surelink.radius.model.User;
import org.surelink.radius.model.Online;
import org.surelink.radius.utils.DateTimeUtil;
import org.tinyradius.attribute.IntegerAttribute;
import org.tinyradius.attribute.RadiusAttribute;
import org.tinyradius.packet.AccountingRequest;


/**
 * 记账更新包处理
 */
public class AcctUpdateMiddleware implements AcctMiddleware
{

    private static final Logger logger = Logger.getLogger(AcctUpdateMiddleware.class);

    private static final Logger acctlog = Logger.getLogger("acct");

    @Autowired
    private OnlineCache onlineCache;

    @Autowired
    private UserCache userCache;

    public void onAcct(User user, AccountingRequest request) throws Exception {

        if(request.getAcctStatusType()!=AccountingRequest.ACCT_STATUS_TYPE_INTERIM_UPDATE)
            return;

        String client = request.getAttributeValue("NAS-IP-Address");
        Online online = onlineCache.get(client, request.getAttributeValue("Acct-Session-Id"));
        if (online == null) {
            if (logger.isInfoEnabled())
                logger.info(String.format("收到记账更新包，但是用户在线记录[%s]不存在",user.getUserName()));

            if (user == null) {
                if (logger.isInfoEnabled())
                    logger.info(String.format("收到记账更新包，但是用户[%s]不存在",user.getUserName()));
                return;
            }
            online = new Online();
            online.setAcctStart(DateTimeUtil.getDateTimeString());
            online.setClientAddress(client);
            online.setIpAddress(request.getAttributeValue("Framed-IP-Address"));
            online.setMacAddress(request.getAttributeValue("Calling-Station-Id"));
            online.setNasPort(request.getAttributeValue("NAS-Port"));
            online.setSessionId(request.getAttributeValue("Acct-Session-Id"));
            online.setUserName(user.getUserName());

            // 计算起始时间
            RadiusAttribute attr = request.getAttribute("Acct-Session-Time");
            int sessionTime = ((IntegerAttribute) attr).getAttributeValueInt();
            String updateTime = DateTimeUtil.getDateTimeString();
            String startTime = DateTimeUtil.getPreviousDateTimeBySecondString(updateTime, sessionTime);

            online.setAcctStart(startTime);
            online.setStartSource(AccountingRequest.ACCT_STATUS_TYPE_INTERIM_UPDATE);// 上线包来源(1=start,3=interim,2=stop,7=nas-acct-start,8=nas-acct-stop)
            onlineCache.set(online);
        } else {
            online.setIpAddress(request.getAttributeValue("Framed-IP-Address"));
            onlineCache.set(online);
        }

        if (logger.isInfoEnabled())
            logger.info(String.format("用户[%s]记账更新包处理成功",user.getUserName()));
    }
}
